package me.qi.kancha.support;

import cn.hutool.core.codec.Base64;
import com.xhyt.common.resource.support.TokenPrincipal;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.util.ObjectUtils;

import java.util.HashSet;
import java.util.Set;

/**
 * @author sun
 * @date 2022/6/26 19:51
 * @modified By：
 */
public class U {
    public static String[] getNullPropertyNames ( Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set< String> emptyNames = new HashSet<String>();
        for(java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    /**
     * 客户端登录不能使用该方法
     *
     * @return
     */
    public static String currentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            throw new RuntimeException("未登录");
        }
        TokenPrincipal principal = (TokenPrincipal) authentication.getPrincipal();
        return (String) principal.getPrincipal().get("entityId");
    }

    /**
     * 返回clientId:grantType
     *
     * @return
     */
    public static String clientEntity() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            throw new RuntimeException("未登录");
        }
        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication;
        String grantType = oAuth2Authentication.getOAuth2Request().getGrantType();
        return String.format("%s:%s", oAuth2Authentication.getOAuth2Request().getClientId(), grantType);
    }

    /**
     * clientId
     * @return
     */
    public static String clientId() {
        OAuth2Authentication authentication = (OAuth2Authentication)
                SecurityContextHolder.getContext().getAuthentication();
        return authentication.getOAuth2Request().getClientId();
    }

    public static String markTypeStr(String customMark) {
        return ObjectUtils.isEmpty(customMark) ? "defaultWatermark" : Base64.encode(customMark);
    }

    public static String fromMarkTypeStr(String markTypeStr) {
        return "defaultWatermark".equals(markTypeStr) ? null : new String(Base64.decode(markTypeStr));
    }
}
